//
//  TestViewController.m
//  怎么说呢
//
//  Created by 杜远洋 on 15-1-3.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "CarTypeViewController.h"
#import "CarTypeModel.h"
#import "CustomCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "DetailCarTypeViewController.h"
#import "Masonry.h"
#import "AFJSONRequestOperation.h"
@interface  CarTypeViewController()<UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation CarTypeViewController
- (void)dealloc
{
 
    [_titleLabel release];
    [_header release];
    [_mySeperateView release];
    [_brandArray release];
    [_collectArray release];
    [_collection release];

    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectArray = [NSMutableArray array];
        self.brandArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self myConnection];
    [self createColleaction];
    self.navigationItem.title = @"车型";
    
}

- (void)changeBackgroundColor
{
    NSUserDefaults *myNight = [NSUserDefaults standardUserDefaults];
    if ([[myNight objectForKey:@"night"] isEqualToString:@"0"]) {
        [self.view setBackgroundColor:[UIColor colorWithRed:238/255.0f green:233/255.0f blue:233/255.0f alpha:1]];
      
        [self.header setBackgroundColor:[UIColor whiteColor]];
        [self.titleLabel setTextColor:[UIColor blackColor]];
    }
    else
    {
        [self.view setBackgroundColor:[UIColor colorWithRed:54/255.0f green:54/255.0f blue:54/255.0f alpha:1]];
        [self.header setBackgroundColor:[UIColor lightGrayColor]];
        [self.titleLabel setBackgroundColor:[UIColor lightGrayColor]];

    }
    
   
}
- (void)myConnection
{
    NSString *str = [NSString stringWithFormat:@"http://mi.xcar.com.cn/interface/xcar/GetBrands.php"];
    
    //数据没有这个格式  所以我们手动添加
    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *array = [JSON objectForKey:@"letters"];
        for (NSDictionary *dic in array) {
            CarTypeModel *model = [[CarTypeModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.collectArray addObject:model];
            
            [model release];
        }
        [self.collection reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"%@",error);
    }];
    
    [operation start];
    
  
}

- (void)createColleaction
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    [flow setItemSize:CGSizeMake(TYPE_SCREEN_WIDTH/5, TYPE_SCREEN_WIDTH * 2 / 9)];
    [flow setMinimumLineSpacing:(TYPE_SCREEN_WIDTH - TYPE_SCREEN_WIDTH * 2 / 15)/ 8];
    
    
    [flow setScrollDirection:UICollectionViewScrollDirectionVertical];
    [flow setSectionInset:UIEdgeInsetsMake(TYPE_SCREEN_WIDTH/15, TYPE_SCREEN_WIDTH/20, TYPE_SCREEN_WIDTH/15, TYPE_SCREEN_WIDTH/20)];
    [flow setHeaderReferenceSize:CGSizeMake(100, 25)];
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, TYPE_SCREEN_WIDTH, TYPE_SCREEN_HEIGHT - TYPE_SCREEN_WIDTH / 70 * 4 - 49) collectionViewLayout:flow];
    
    [self.collection setBackgroundColor:[UIColor clearColor]];
    [self.collection registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"cell1"];
    self.collection.dataSource = self;
    self.collection.delegate = self;
    [self.collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:self.collection];
    [_collection release];
    [flow release];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return [self.collectArray count];
}

#pragma mark - 设置section的header

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    self.header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
   

    
    //设置label属性调整宽度为全屏，然后修改夜间模式颜色
   
    
    self.titleLabel = [UILabel new];
    [_header addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_header.mas_left).with.offset(5);
        make.top.equalTo(_header.mas_top);
        make.height.equalTo(_header.mas_height);
        make.width.equalTo(_header.mas_width);
    }];
    
//    [self.titleLabel setBackgroundColor:[UIColor whiteColor]];
    CarTypeModel *model = [self.collectArray objectAtIndex:indexPath.section];
    [self.titleLabel setText:model.letter];
    self.titleLabel.text = [self.titleLabel.text capitalizedString];
    [self.titleLabel setTextAlignment:NSTextAlignmentLeft];
    [self.titleLabel setFont:[UIFont systemFontOfSize:20]];
    
    //夜间模式
    NSUserDefaults *myNight = [NSUserDefaults standardUserDefaults];
    if ([[myNight objectForKey:@"night"] isEqualToString:@"0"]) {
        
        [self.header setBackgroundColor:[UIColor whiteColor]];
        [self.titleLabel setBackgroundColor:[UIColor whiteColor]];
    }
    else
    {
       
        [self.header setBackgroundColor:[UIColor lightGrayColor]];
        [self.titleLabel setBackgroundColor:[UIColor lightGrayColor]];
        
    }

    [_titleLabel release];
    
    
    return _header;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    CarTypeModel *model = [self.collectArray objectAtIndex:section];
    
    return [model.brands count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell1" forIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor clearColor]];
    CarTypeModel *model = [self.collectArray objectAtIndex:indexPath.section];
    NSDictionary *dic = [model.brands objectAtIndex:indexPath.item];
    NSString *name = [dic objectForKey:@"name"];
    NSString *picture = [dic objectForKey:@"icon"];
    
    [cell.myField setText:name];
   
    [cell.myImage setImageWithURL:[NSURL URLWithString:picture] placeholderImage:[UIImage imageNamed:@"placeHolder.png"] options:SDWebImageRetryFailed];
    

    NSUserDefaults *myNight = [NSUserDefaults standardUserDefaults];
    
    if ([[myNight objectForKey:@"night"] isEqualToString:@"0"]) {
        [cell.locationView setBackgroundColor:[UIColor whiteColor]];
        [cell.myField setTextColor:[UIColor blackColor]];
    }
    else
    {
        [cell.locationView setBackgroundColor:[UIColor lightGrayColor]];
        [cell.myField setTextColor:[UIColor colorWithRed:65/255.0f green:105/255.0f blue:255/255.0f alpha:1]];
        
    }
    

    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CarTypeModel *model = [self.collectArray objectAtIndex:indexPath.section];
    NSDictionary *dic = [model.brands objectAtIndex:indexPath.item];
    
    
    
    
    DetailCarTypeViewController *detail = [[DetailCarTypeViewController alloc] init];

 
//    __block UIViewController *weakSelf = self;
    //遮挡特效视图
    self.mySeperateView = [[UIButton alloc] initWithFrame:CGRectMake(TYPE_SCREEN_WIDTH/2, 0, 1, TYPE_SCREEN_HEIGHT - TYPE_SCREEN_WIDTH * 4 / 75)];
//    self.mySeperateView = [UIButton new];
    [self.view addSubview:self.mySeperateView];
//    [self.mySeperateView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(@(weakSelf.view.frame.size.width / 2));
//        make.top.equalTo(weakSelf.view.mas_top);
//        make.width.mas_equalTo(@(1));
//        make.height.mas_equalTo(@(weakSelf.view.frame.size.height - weakSelf.view.frame.size.width * 4 / 75));
//    }];
    [self.mySeperateView setBackgroundColor:[UIColor blackColor]];
    
    
    
    UIImageView *backPicture = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.mySeperateView.frame.size.width, self.mySeperateView.frame.size.height)];
    [backPicture setImage:[UIImage imageNamed:@"bugadi1.jpg"]];
    backPicture.tag = 100;
    [self.mySeperateView addSubview:backPicture];
  

    
    NSArray *array = [dic objectForKey:@"subBrands"];
    [detail.tableArray addObjectsFromArray:array];
    
    //添加透明薄膜
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 20)];
    [button setBackgroundColor:[UIColor grayColor]];
    [button setAlpha:0];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    //button上添加label标注车的类型
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(TYPE_SCREEN_WIDTH * 3/10 , TYPE_SCREEN_WIDTH / 15, TYPE_SCREEN_WIDTH * 2 / 5, TYPE_SCREEN_WIDTH * 2 / 25)];
    [myLabel setBackgroundColor:[UIColor whiteColor]];
    [myLabel setText:[dic objectForKey:@"name"]];
    myLabel.layer.cornerRadius = 10;
    myLabel.layer.masksToBounds = YES;
    
    [myLabel setTextAlignment:NSTextAlignmentCenter];
    [button addSubview:myLabel];
    [myLabel release];
    
    
    
    detail.view.tag = 10;
    [self addChildViewController:detail];
    

    [self.view addSubview:detail.view];
    [detail.view setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.0]];
    
    //设定自定义cell高度：
    NSArray *subBrands = [dic objectForKey:@"subBrands"];
    NSInteger count = 0;
    NSArray *seriesArray = [NSArray array];
    for (int i = 0; i < [subBrands count]; i++) {
        NSDictionary *dic = [subBrands objectAtIndex:i];
        seriesArray = [dic objectForKey:@"series"];
        count = count + [seriesArray count];
    }
    self.myHeight = 0;
    if (count >= 5) {
        self.myHeight = TYPE_SCREEN_HEIGHT * 2 / 3;
        
    }
    else
    {
        self.myHeight = TYPE_SCREEN_WIDTH * 16 / 75 * count + [subBrands count] * 20;
    }
    
#pragma mark - 动画实现页面的跳转 设置frame
    
    [detail.view setFrame:CGRectMake(TYPE_SCREEN_WIDTH/20 , TYPE_SCREEN_HEIGHT * 2 / 3, TYPE_SCREEN_WIDTH - TYPE_SCREEN_WIDTH/10, self.myHeight)];
    
    [UIView animateWithDuration:1.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [detail.view setFrame:CGRectMake(TYPE_SCREEN_WIDTH/20 , TYPE_SCREEN_HEIGHT / 8, TYPE_SCREEN_WIDTH - TYPE_SCREEN_WIDTH/10, self.myHeight)];
        [detail.view setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.4]];
        
        
        [button setAlpha:0.4f];
        button.frame = CGRectMake(0, 0, TYPE_SCREEN_WIDTH, TYPE_SCREEN_HEIGHT - 20);
        
        self.mySeperateView.frame = CGRectMake(0, 0, TYPE_SCREEN_WIDTH, TYPE_SCREEN_HEIGHT);
        [backPicture setFrame:CGRectMake(0, 0, TYPE_SCREEN_WIDTH, TYPE_SCREEN_HEIGHT)];
        
     
    } completion:^(BOOL finished) {
        //关闭collection的点击功能
        self.collection.userInteractionEnabled = NO;
        NSLog(@"移动完成");
    }];
    
    
    
    [_mySeperateView release];

    [detail release];
    
}

#pragma mark - 实现页面的回收，也就是还原
- (void)buttonAction:(id)sender
{
    
    UIButton *button = (UIButton *)sender;
    
    UIView *detailView = [self.view viewWithTag:10];
    
    [detailView setFrame:CGRectMake(TYPE_SCREEN_WIDTH/20 , TYPE_SCREEN_HEIGHT / 5, TYPE_SCREEN_WIDTH - TYPE_SCREEN_WIDTH/10, self.myHeight)];
    [UIView animateWithDuration:0.05 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [detailView setFrame:CGRectMake(TYPE_SCREEN_WIDTH/20 , - TYPE_SCREEN_HEIGHT * 2 / 3, TYPE_SCREEN_WIDTH - TYPE_SCREEN_WIDTH/10, self.myHeight)];
        detailView.alpha = 0;
        
        
        [button setAlpha:0];
        button.frame = CGRectMake(0, - TYPE_SCREEN_HEIGHT, TYPE_SCREEN_WIDTH, TYPE_SCREEN_HEIGHT - 20);
        
        //视图特效取消
        self.mySeperateView.center = self.view.center;
        self.mySeperateView.frame = CGRectMake(TYPE_SCREEN_WIDTH / 2, 0, 0, TYPE_SCREEN_HEIGHT);
        
        UIImageView *picture = (UIImageView *)[self.mySeperateView viewWithTag:100];
        [picture setFrame:CGRectMake(0, 0, 0, 0)];
        picture.alpha = 0.1;
        
        
    } completion:^(BOOL finished) {

        [detailView removeFromSuperview];
        [button removeFromSuperview];
        
        [self.mySeperateView removeFromSuperview];
        //移动结束后 打开collection的用户交互功能，并移除视图
        self.collection.userInteractionEnabled = YES;
        NSLog(@"移动完成0000");
    }];
 
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.collection reloadData];
    [self changeBackgroundColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
